<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-row gutter={20}>
        <!-- 项目编号和检测地点合并成一行 -->
        <el-col :span="12">
          <el-form-item label="项目编号" prop="projectCode">
            <el-select v-model="dataForm.projectCode" placeholder="请选择项目编号" class="label_len" :disabled="selectDis">
              <el-option v-for="item in projectList" :key="item.prProjectNumber"
                :label="item.prProjectNumber + item.prProjectName" :value="item.prProjectNumber">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="检测地点" prop="testingLocation">
            <el-input v-model="dataForm.testingLocation" placeholder="检测地点"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table v-model="tableData" :data="tableData" style="width: 100%">
        <el-table-column prop="points" label="项目"></el-table-column>
        <el-table-column prop="samplingDepth" label="单位"></el-table-column>

        <!-- 土壤含水率列，包含湿重、干重、土壤含水率百分比的输入框 -->
        <el-table-column label="测定点">
          <el-table-column label="1">
            <template slot-scope="scope">
              <el-input v-model="dataForm[scope.row.wetWeight]" :placeholder="'请输入' + scope.row.points" size="small"
                @input="handleInputChange(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="2">
            <template slot-scope="scope">
              <el-input v-model="dataForm[scope.row.dryWeight]" :placeholder="'请输入' + scope.row.points" size="small"
                @input="handleInputChange(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="3">
            <template slot-scope="scope">
              <el-input v-model="dataForm[scope.row.soilMoisture]" :placeholder="'请输入' + scope.row.points" size="small"
                @input="handleInputChange(scope.row)"></el-input>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 土壤坚实度列 -->
        <el-table-column prop="soilSolidity" label="范围值">
          <template slot-scope="scope">
            <el-input v-model="dataForm[scope.row.soilSolidity]" :placeholder="scope.row.points + '范围'" size="small"
              disabled></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        projectCode: '',
        testingLocation: '',
        temperature1: '',
        temperature2: '',
        temperature3: '',
        temperatureRange: '',
        humidity1: '',
        humidity2: '',
        humidity3: '',
        humidityRange: '',
        detectPeople: '',
        recorders: '',
        checkers: '',
        pdfPath: '',
        wordPath: '',
        status: '',
        userId: ''
      },
      selectDis:false,
      projectList: [],
      tableData: [
        { points: '环境温度', samplingDepth: "℃", type: 1, wetWeight: "temperature1", dryWeight: "temperature2", soilMoisture: "temperature3", soilSolidity: "temperatureRange" },
        { points: '环境湿度', samplingDepth: "%", type: 2, wetWeight: "humidity1", dryWeight: "humidity2", soilMoisture: "humidity3", soilSolidity: "humidityRange" }
      ],
      dataRule: {
        projectCode: [
          { required: true, message: '项目编号不能为空', trigger: 'blur' }
        ],
        testingLocation: [
          { required: true, message: '检测地点不能为空', trigger: 'blur' }
        ],
        temperature1: [
          { required: true, message: '环境温度1不能为空', trigger: 'blur' }
        ],
        temperature2: [
          { required: true, message: '环境温度2不能为空', trigger: 'blur' }
        ],
        temperature3: [
          { required: true, message: '环境温度3不能为空', trigger: 'blur' }
        ],
        temperatureRange: [
          { required: true, message: '环境温度范围不能为空', trigger: 'blur' }
        ],
        humidity1: [
          { required: true, message: '环境湿度1不能为空', trigger: 'blur' }
        ],
        humidity2: [
          { required: true, message: '环境湿度2不能为空', trigger: 'blur' }
        ],
        humidity3: [
          { required: true, message: '环境湿度3不能为空', trigger: 'blur' }
        ],
        humidityRange: [
          { required: true, message: '环境湿度范围不能为空', trigger: 'blur' }
        ],
        detectPeople: [
          { required: true, message: '检测人不能为空', trigger: 'blur' }
        ],
        recorders: [
          { required: true, message: '记录人不能为空', trigger: 'blur' }
        ],
        checkers: [
          { required: true, message: '校核人不能为空', trigger: 'blur' }
        ],
        pdfPath: [
          { required: true, message: 'pdf存放路径不能为空', trigger: 'blur' }
        ],
        wordPath: [
          { required: true, message: 'word存放路径不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '审核状态不能为空', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '创建人不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted (){
    this.getprojectList()
  },
  methods: {
    // 处理输入框内容变化
    handleInputChange(row) {
      // 只有当所有输入框都有值时才进行计算
      const wetWeight = parseFloat(this.dataForm[row.wetWeight]);
      const dryWeight = parseFloat(this.dataForm[row.dryWeight]);
      const soilMoisture = parseFloat(this.dataForm[row.soilMoisture]);

      if (this.isValidInput(wetWeight, dryWeight, soilMoisture)) {
        this.calculateSoilSolidity(row, wetWeight, dryWeight, soilMoisture);
      } else {
        // 如果数据不完整，清空范围值
        this.$set(this.dataForm, row.soilSolidity, '');
      }
    },

    // 判断输入的湿重、干重和湿度是否有效
    isValidInput(wetWeight, dryWeight, soilMoisture) {
      return !isNaN(wetWeight) && !isNaN(dryWeight) && !isNaN(soilMoisture) &&
        wetWeight !== null && dryWeight !== null && soilMoisture !== null;
    },

    // 计算土壤坚实度范围
    calculateSoilSolidity(row, wetWeight, dryWeight, soilMoisture) {
      const minValue = Math.min(wetWeight, dryWeight, soilMoisture);
      const maxValue = Math.max(wetWeight, dryWeight, soilMoisture);

      // 更新soilSolidity为范围值
      this.$set(this.dataForm, row.soilSolidity, `${minValue} ~ ${maxValue}`);
    },
    //获取项目列表
    getprojectList() {
      this.$http({
        url: this.$http.adornUrl(`/reportapproval/product/getProjectNumber`),
        method: 'post',
        data: this.$http.adornData({
        })
      }).then((data) => {
        if (data && data.code === 0) {
          console.log(data.productList)
          this.projectList = data.productList
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    init(id) {
      this.dataForm.id = id || 0
      this.selectDis = false
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/reportapproval/temperaturehumidity/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then((data) => {
            if (data && data.code === 0) {
              this.dataForm.projectCode = data.temperatureHumidity.projectCode
              this.dataForm.testingLocation = data.temperatureHumidity.testingLocation
              this.dataForm.temperature1 = data.temperatureHumidity.temperature1
              this.dataForm.temperature2 = data.temperatureHumidity.temperature2
              this.dataForm.temperature3 = data.temperatureHumidity.temperature3
              this.dataForm.temperatureRange = data.temperatureHumidity.temperatureRange
              this.dataForm.humidity1 = data.temperatureHumidity.humidity1
              this.dataForm.humidity2 = data.temperatureHumidity.humidity2
              this.dataForm.humidity3 = data.temperatureHumidity.humidity3
              this.dataForm.humidityRange = data.temperatureHumidity.humidityRange
              this.dataForm.detectPeople = data.temperatureHumidity.detectPeople
              this.dataForm.recorders = data.temperatureHumidity.recorders
              this.dataForm.checkers = data.temperatureHumidity.checkers
              this.dataForm.pdfPath = data.temperatureHumidity.pdfPath
              this.dataForm.wordPath = data.temperatureHumidity.wordPath
              this.dataForm.status = data.temperatureHumidity.status
              this.dataForm.userId = data.temperatureHumidity.userId
              this.selectDis=true
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/reportapproval/temperaturehumidity/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'projectCode': this.dataForm.projectCode,
              'testingLocation': this.dataForm.testingLocation,
              'temperature1': this.dataForm.temperature1,
              'temperature2': this.dataForm.temperature2,
              'temperature3': this.dataForm.temperature3,
              'temperatureRange': this.dataForm.temperatureRange,
              'humidity1': this.dataForm.humidity1,
              'humidity2': this.dataForm.humidity2,
              'humidity3': this.dataForm.humidity3,
              'humidityRange': this.dataForm.humidityRange,
              'detectPeople': this.dataForm.detectPeople,
              'recorders': this.dataForm.recorders,
              'checkers': this.dataForm.checkers,
              'pdfPath': this.dataForm.pdfPath,
              'wordPath': this.dataForm.wordPath,
              'status': this.dataForm.status,
              'userId': this.dataForm.userId
            })
          }).then((data) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.warning(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
